package com.bfxy.rabbitmq.api.confirmlistener;

import java.io.IOException;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.ConfirmListener;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

public class Sender4ConfirmListener {

	public static void main(String[] args) throws Exception {

		Connection connection = null;
		Channel channel = null;
		try {
			// 1 创建ConnectionFactory
			ConnectionFactory connectionFactory = new ConnectionFactory();
			connectionFactory.setHost("192.168.218.21");
			connectionFactory.setPort(5672);
			connectionFactory.setVirtualHost("/");

			// 2 创建Connection
			connection = connectionFactory.newConnection();
			// 3 创建Channel
			channel = connection.createChannel();

			// 4 声明
			String exchangeName = "test_confirmlistener_exchange";
			String routingKey1 = "confirm.save";
			String exchangeType = "topic";
			channel.exchangeDeclare(exchangeName, exchangeType, true, false, false, null);
			channel.confirmSelect(); // 开启确认模式
			channel.addConfirmListener(new ConfirmListener() { // 添加监听
				// 失败
				@Override
				public void handleNack(long deliveryTag, boolean multiple) throws IOException {
					System.err.println("------- error ---------");
				}
				// 成功
				@Override
				public void handleAck(long deliveryTag, boolean multiple) throws IOException {
					System.err.println("------- ok ---------");
				}
			});

            // 5 发送
			String msg = "Hello World RabbitMQ 4 Confirm Listener Message ...";
			channel.basicPublish(exchangeName, routingKey1 , null , msg.getBytes());
		} catch (Exception e) {
			e.printStackTrace();
		} /*finally {
			if (channel != null) {
				channel.close();
			}
			if (connection != null) {
				connection.close();
			}
		}*/   // 不要关闭资源，ConfirmListener会监听broker的应答执行回调函数
 
	}
	
}
